package com.winit.openapi.erp.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.erp.spi.ebay.EbayAccountService;
import com.winit.erp.spi.ebay.EbayQueryDataService;
import com.winit.erp.spi.ebay.command.EbayQueryCommand;
import com.winit.erp.spi.ebay.vo.EbayReplenishment;
import com.winit.erp.spi.ebay.vo.EbaySellerAuthorize;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;

/**
 * Ebay查询接口Controller
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * jianhua.huang 	1.0  		2015-7-1 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/ebay/query")
public class EbayQueryDataController extends BaseController {
    
    private static final Logger logger = LoggerFactory.getLogger(EbayQueryDataController.class);

	@Resource
	private EbayAccountService ebayAccountService;

	@Resource
	private EbayQueryDataService ebayQueryDataService;

	/**
	 * 查询Ebay授权结果 TODO Add comments here.
	 */
	@RequestMapping(value = "/querySellerAuthorizeResult")
	public String querySellerAuthorize(
			@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			// 校验参数
			validISPOrder(json);
			EbayQueryCommand command = new EbayQueryCommand();
			Searchable searchable = Searchable.newSearchable();
			searchable.setPage((json.getInteger("pageNo") - 1),json.getInteger("pageSize"));
			command.setSearchable(searchable);
			Page<EbaySellerAuthorize> pagelist = ebayAccountService
					.querySellerAuthorizeResult(command);
			if (pagelist != null) {
				List<Map<String, Object>> datalist = buildReturnSellerAuthorizeList(pagelist
						.getContent());
				Map<String, Object> pageMap = new HashMap<String, Object>();
                pageMap.put("pageNo",pagelist.getPageable().getPageNumber() + 1);
				pageMap.put("pageSize", pagelist.getPageable().getPageSize());
				pageMap.put("totalCount", pagelist.getTotalElements());

				Map<String, Object> data = new HashMap<String, Object>();
				data.put("list", datalist);
				data.put("pageParams", pageMap);
				responseMsg.setData(data);
			}
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		return SUCCESS;
	}

	/**
	 * Ebay查询补货数据接口
	 * 
	 */
	@RequestMapping(value = "/queryReplenishment")
	public String queryReplenishment(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg) {
		Object obj = requestMsg.getData();
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			// 校验参数
			ValidateUtil.validNotNull(json, "destinationWarehouseName");
			ValidateUtil.validMaxLength(json, "destinationWarehouseName", 50);
			validISPOrder(json);
			EbayQueryCommand queryCommand = new EbayQueryCommand();
			queryCommand.setDestinationWarehouseName(json.getString("destinationWarehouseName"));
			Searchable searchable = Searchable.newSearchable();
		    searchable.setPage((json.getInteger("pageNo") - 1),json.getInteger("pageSize"));		
			searchable.addSearchFilter("w.name", SearchOperator.eq,
					queryCommand.getDestinationWarehouseName());
			queryCommand.setSearchable(searchable);
			Page<EbayReplenishment> pagelist = ebayQueryDataService
					.queryReplenishment(queryCommand);
			if (pagelist != null) {
				List<Map<String, Object>> datalist = buildReturnReplenishmentList(pagelist
						.getContent());
				Map<String, Object> pageMap = new HashMap<String, Object>();
			    pageMap.put("pageNo",pagelist.getPageable().getPageNumber() + 1);
				pageMap.put("pageSize", pagelist.getPageable().getPageSize());
				pageMap.put("totalCount", pagelist.getTotalElements());

				Map<String, Object> data = new HashMap<String, Object>();
				data.put("list", datalist);
				data.put("pageParams", pageMap);
				responseMsg.setData(data);
			}else{
			    logger.info("queryReplenishment result is null,params:"+ JSON.toJSONString(queryCommand));
			}
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		return SUCCESS;
	}

	/**
	 * 是否开启上传Ebay智能补货数据
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value = "/uploadReplenishment")
	public String uploadReplenishment(@ModelAttribute RequestMsg requestMsg,
			@ModelAttribute ResponseMsg responseMsg){
		Object obj = requestMsg.getData();
		if (obj instanceof JSONObject) {
			JSONObject json = (JSONObject) obj;
			// 校验参数
			ValidateUtil.validNotNull(json, "c_bpartner_id");
			ValidateUtil.validMaxLength(json, "no_upload", 1);
			
		}else{
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
		}
		return SUCCESS;
	}
	
	/**
	 * 验证参数 TODO Add comments here.
	 * 
	 * @param json
	 */
	private void validISPOrder(JSONObject json) {
		if (json.containsKey("pageNo") && json.containsKey("pageSize")) {
			ValidateUtil.validInteger(json, "pageNo");
			// pageSize
			ValidateUtil.validInteger(json, "pageSize");

			if (isExistValue(json, "pageNo")) {
				int pageNo = json.getInteger("pageNo");
				if (pageNo < 1) {
					throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
				}
			}
			if (isExistValue(json, "pageSize")) {
				int pageSize = json.getInteger("pageSize");
				if (pageSize < 1) {
					throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
				}
			}
		}else{
			throw new ApiException(ErrorCode.FIELD_ERROR,"pageSize or pageNo");
		}
	}

	// 判断非必填字段是否有值
	public boolean isExistValue(JSONObject jsonObject, String key) {
		if (jsonObject.containsKey(key)) {
			return !"".equals(jsonObject.getString(key).trim());
		}
		return false;
	}

	/**
	 * 构建智能补货返回数据
	 * 
	 * @param listReplenishments
	 * @return
	 */
	private List<Map<String, Object>> buildReturnReplenishmentList(
			List<EbayReplenishment> listReplenishments) {
		List<Map<String, Object>> rslist = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		for (EbayReplenishment replenishment : listReplenishments) {
			map = new HashMap<String, Object>();
			map.put("deliveryWarehouseName",
					replenishment.getDeliveryWarehouseName());
			map.put("destinationWarehouseName",
					replenishment.getDestinationWarehouseName());
			map.put("modesOfTransportation",
					replenishment.getModesOfTransportation());
			map.put("productCode", replenishment.getProductCode());
			map.put("specifications", replenishment.getSpecifications());
			map.put("librariesNumber", replenishment.getLibrariesNumber());
			map.put("transitNumber", replenishment.getTransitNumber());
			map.put("winitCustomName", replenishment.getWinitCustomName());
			map.put("safetyStock", replenishment.getSafetyStock());
			map.put("averageDailySales", replenishment.getAverageDailySales());
			map.put("replenishmentNumber",
					replenishment.getReplenishmentNumber());
			map.put("availableInventory", replenishment.getAvailableInventory());
			map.put("availableDays", replenishment.getAvailableDays());
			map.put("isActive", replenishment.getIsActive());
			map.put("updated", replenishment.getUpdated());
			rslist.add(map);
		}
		return rslist;
	}

	/**
	 * 构建查询授权返回数据
	 */
	private List<Map<String, Object>> buildReturnSellerAuthorizeList(
			List<EbaySellerAuthorize> listAuthorizes) {
		List<Map<String, Object>> rslist = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		for (EbaySellerAuthorize authorize : listAuthorizes) {
			map = new HashMap<String, Object>();
			map.put("ebaySellerID", authorize.getEbaySellerID());
			map.put("ebayToken", authorize.getEbayToken());
			map.put("winitSellerID", authorize.getWinitSellerID());
			map.put("winitSellerName", authorize.getWinitSellerName());
			if(StringUtils.isEmpty(authorize.getIsActivate())){
				map.put("isActive", "N");
			}else{
				map.put("isActive", authorize.getIsActivate());
			}
			rslist.add(map);
		}
		return rslist;
	}
}
